package com.capgemini.scaffold.config;

import com.capgemini.scaffold.common.BusinessException;
import com.capgemini.scaffold.common.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseBean sysException(Exception e) {
        log.error("系统异常", e);
        return ResponseBean.failed();
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResponseBean sysException(BusinessException e) {
        log.error("业务异常", e);
        return ResponseBean.failed(e.getCode(), e.getMessage(), e.getErrorData());
    }

    //处理检验异常
    //@ExceptionHandler 统一处理方法抛出的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseBean handleError(MethodArgumentNotValidException e){
        log.warn("数据校验异常",e.getMessage());
        BindingResult bindingResult= e.getBindingResult();
        String errorMsg = "";
        //FieldError获取所有字段的错误信息
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            //getDefaultMessage 错误消息
            errorMsg += fieldError.getDefaultMessage();
        }
        return ResponseBean.failed(HttpStatus.BAD_REQUEST.value(), errorMsg);
    }

}
